<template>
  <!-- 电话和地址 -->
  <div class="contact-tab">
    <el-form
      ref="form"
      inline
      :model="temp01"
    >
      <el-form-item
        label="电话:"
        prop="phone"
      >
        <el-input v-model.trim="temp01.csmPhone" placeholder="请输入" style="width: 250px;" />
      </el-form-item>
      <el-form-item label="联系人:">
        <el-input v-model.trim="temp01.contact" placeholder="请输入" style="width: 250px;" />
        <el-button
          type="primary"
          style="margin-left: 10px;"
          @click="addMessage01"
        >添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      border
      class="addressTableStyle"
      :row-class-name="tableRowClassName"
      element-loading-text="加载中"
      :column="tableData01.column"
      :data="tableData01.data"
      height="170"
    />
    <el-divider />

    <el-form
      ref="form"
      :model="temp02"
      inline
    >
      <el-form-item label="就近门市:">
        <el-tree-select
          ref="select"
          v-model="temp02.orgName"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgName',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="地址:">
        <el-cascader ref="cascader" v-model="AddressData" style="width: 300px;" :props="addressProps" clearable @change="selectCascader" />
        <el-input v-model="temp02.csmAddress" style="width: 250px;" />
        <!-- <el-button type="primary" icon="el-icon-location" style="width: 70px;" size="mini" @click="location">定位</el-button> -->
        <el-input-number
          v-model="temp02.csmFloor"
          :controls="false"
          :min="1"
          :max="99"
          :precision="0"
          style="width: 100px;"
        />
        层
        <el-button
          type="primary"
          style="margin-left: 10px;"
          @click="addMessage02"
        >添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData02.column"
      height="170px"
      :data="tableData02.data"
      :total="tableData02.total"
      custom-column
    />

    <location ref="location" />
  </div>
</template>

<script>
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { selectAreaCode, deleteCsmPhone } from '@/api'
  import Location from './mapAddress'

  export default {
    name: 'tab-edit-contaction',
    components: {
      Location
    },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      temp: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        type: '',
        options: [],
        AddressData: [],
        provinceList: [], // 省
        cityList: [], // 市
        countryList: [], // 区
        streetList: [], // 街道
        addressCascader: [], // 级联选择地址
        temp01: {
          contact: '', // 联系人
          csmPhone: ''
        },
        temp02: {
          orgName: '',
          csmAddress: '',
          csmFloor: undefined
        },
        tableData01: {
          total: 0,
          column: [
            {
              type: 'index',
              label: '#',
              width: 30
            },
            {
              prop: 'csmPhone',
              label: '电话',
              render: (h, scope) => scope.row._edit ? <el-input v-model={scope.row[scope.column.property]} onInput={val => scope.row[scope.column.property] = val.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/, '$1')} size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'contact',
              label: '联系人',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input size='mini' value={row[column.property]} onInput={(val) => { row[column.property] = val }}></el-input>
                  ) : (<span>{row[column.property]}</span>)}
                </div>
                )
              }
            // width: 110
            },
            {
              prop: 'cpStatus',
              label: '状态',
              render: (h, { row }) => <span>{ this.cpStatusFormat(row) }</span>
            // width: 110
            },
            {
              prop: 'isMain',
              label: '默认电话',
              align: 'center',
              render: (h, { row }) => row.isMain === 1 ? <i class='el-icon-success' style='color: #F56C6C;' /> : <span></span>
            },
            {
              label: '操作',
              align: 'center',
              width: 150,
              render: (h, { row, $index }) => {
                return (
                  row.cpStatus !== -1 && <div >
                    {
                    row.isMain === 1
                      ? row._edit ? <span>
                                      <el-link underline={false} onClick={ () => { this.handleSave(row) } }>保存</el-link>
                                    </span>
                        : <span>
                            <el-link underline={false} onClick={ () => { this.handleEdit(row) } }>编辑</el-link>
                          </span>
                      : row._edit ? <span>
                                      <el-link underline={false} onClick={ () => { this.setDefaultInvoice(row) } }>设为默认</el-link>
                                      <el-link underline={false} onClick={ () => { this.handleSave(row) } }>保存</el-link>
                                    </span>
                        : <span>
                            <el-link underline={false} onClick={ () => { this.setDefaultInvoice(row) } }>设为默认</el-link>
                            <el-link underline={false} onClick={ () => { this.handleEdit(row) } }>编辑</el-link>
                          </span>
                    }
                    <el-link underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>注销</el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        },
        tableData02: {
          total: 0,
          column: [
            {
              prop: 'provinceName',
              width: 140,
              label: '省',
              render: (h, { row, $index, column }) => {
                return (
                <div>{row._edit ? (
                    <el-select size='mini' value={row[column.property]} style='width: 120px' onChange={(val) => { this.changeProvince(row, column, val) }}>{this.provinceList.map((option) => {
                        return <el-option size='mini' label={option.areaName} value={option.areaCode}></el-option>
                      })}
                    </el-select>
                  )
                  : (<span >{row[column.property]}</span>)}  </div>
                )
              }
            },
            {
              prop: 'cityName',
              width: 140,
              label: '市',
              render: (h, { row, $index, column }) => {
                return (
                <div>{row._edit ? (
                    <el-select size='mini' value={row[column.property]} style='width: 120px' onvisible-change={async() => this.cityList = await this.getAddressList(row.provinceCode ? row.provinceCode : -1)} onChange={(val) => { this.changeCity(row, column, val) }}>{this.cityList.map((option) => {
                        return <el-option size='mini' label={option.areaName} value={option.areaCode}></el-option>
                      })}
                    </el-select>
                  )
                  : (<span >{row[column.property]}</span>)}  </div>
                )
              }
            },
            {
              prop: 'countryName',
              width: 140,
              label: '区/县',
              render: (h, { row, $index, column }) => {
                return (
                <div>{row._edit ? (
                    <el-select size='mini' value={row[column.property]} onvisible-change={async() => this.countryList = await this.getAddressList(row.cityCode ? row.cityCode : -1)} style='width: 120px' onChange={(val) => { this.changeCountry(row, column, val) }}>{this.countryList.map((option) => {
                        return <el-option size='mini' label={option.areaName} value={option.areaCode}></el-option>
                      })}
                    </el-select>
                  )
                  : (<span >{row[column.property]}</span>)}  </div>
                )
              }
            },
            {
              prop: 'streetName',
              width: 140,
              label: '街道',
              render: (h, { row, $index, column }) => {
                return (
                <div>{row._edit ? (
                    <el-select size='mini' value={row[column.property]} style='width: 120px' onvisible-change={async() => this.streetList = await this.getAddressList(row.countryCode ? row.countryCode : -1)} onChange={(val) => { this.changeStreet(row, column, val) }}>{this.streetList.map((option) => {
                        return <el-option size='mini' label={option.areaName} value={option.areaCode}></el-option>
                      })}
                    </el-select>
                  )
                  : (<span >{row[column.property]}</span>)}  </div>
                )
              }
            },
            {
              prop: 'csmAddress',
              label: '地址',
              width: 250,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input size='mini' value={row[column.property]} onInput={(val) => { row[column.property] = val }}></el-input>
                  ) : <span onClick={() => this.openLocation(row)}>
                {row.csmAddressId && (<i class='el-icon-location' style='color: #F56C6C;cursor: pointer;' />)}
                {row.csmAddress}
              </span>}
                </div>
                )
              }
            },
            {
              prop: 'orgName',
              label: '就近门市',
              width: 200,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-tree-select
                    value={row.orgName}
                    clearable={false}
                    class='tree-select'
                    popover-width={360}
                    select-params={
                      { clearable: true,
                      placeholder: '请选择所属单位' }
                    }
                    tree-params= {
                      {
                        'expand-on-click-node': false,
                        'highlight-current': true,
                        props: {
                          value: 'orgName',
                          label: 'orgName',
                          disabled: 'disabled'
                        },
                        data: this.treeData
                      }
                    }
                onnode-click={(val) => this.selectRowTreeChange(val, row)}
                />
                  ) : (<span>{row[column.property]}</span>)}
                </div>
                )
              }

              //
            },
            {
              prop: 'csmFloor',
              align: 'right',
              label: '楼层',
              width: 80,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input-number controls={false} min={0} max={99} precision={0} value={row[column.property]} onInput={(val) => { row[column.property] = val }}></el-input-number>
                  ) : (<span>{row[column.property]}</span>)}
                </div>
                )
              }
            },
            {
              prop: 'isMain',
              align: 'center',
              label: '默认地址',
              fixed: 'right',
              width: 80,
              render: (h, { row }) => row.isMain === 1 ? <i class='el-icon-success' style='color: #F56C6C;' /> : <span></span>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 150,
              render: (h, { row, $index }) => {
                return (
                <div>
                  {
                      row.isMain === 1
                        ? row._edit ? <span>
                                        <el-link underline={false} onClick={ () => { this.handleSave01(row) } }>保存</el-link>
                                      </span>
                          : <span>
                              <el-link underline={false} onClick={ () => { this.handleEdit(row) } }>编辑</el-link>
                            </span>
                        : row._edit ? <span>
                                        <el-link underline={false} onClick={ () => { this.setDefaultInvoice01(row) } }>设为默认</el-link>
                                        <el-link underline={false} onClick={ () => { this.handleSave01(row) } }>保存</el-link>
                                      </span>
                          : <span>
                              <el-link underline={false} onClick={ () => { this.setDefaultInvoice01(row) } }>设为默认</el-link>
                              <el-link underline={false} onClick={ () => { this.handleEdit(row) } }>编辑</el-link>
                            </span>
                    }
                    <el-link underline={false} size='mini' type='danger' onClick={() => this.del01(row, $index)}>注销</el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        },
        addressProps: {
          lazy: true,
          checkStrictly: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
              .then((res) => {
                const nodes = res.data.map((item) => ({
                  value: item.areaCode,
                  label: item.areaName,
                  leaf: level >= 3
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        }
      }
    },
    async created() {
      this.tableData01.defaultData = JSON.parse(JSON.stringify(this.tableData01.data))
      this.provinceList = await this.getAddressList()
    },
    mounted() {
      this.tableData01.data = this.temp.phoneItems
      this.tableData02.data = this.temp.addressItems
    },
    methods: {
      // filtration() {
      //   const temp = this.temp.phoneItems.filter(item => {
      //     if (item.cpStatus !== -1) {
      //       return item
      //     }
      //   })
      //   this.tableData01.data = temp
      // },
      // 设置默认
      setDefaultInvoice(row) {
        console.log(row)
        // row.isMain = 1
        this.tableData01.data.forEach(item => {
          item.isMain = 0
        })
        row.isMain = 1
      },
      setDefaultInvoice01(row) {
        this.tableData02.data.forEach(item => {
          item.isMain = 0
        })
        row.isMain = 1
      },
      // 状态
      cpStatusFormat(row) {
        if (row.cpStatus === -1) {
          return '已注销'
        } else if (row.cpStatus === 2) {
          return '使用中'
        } else if (row.cpStatus === -2) {
          return '已注销'
        }
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        console.log(value)
        console.log(1111)
      },
      selectRowTreeChange(value, row) {
        console.log(row, 'row')
        console.log(value, 'value')
        row.orgName = value.orgName
        row.orgSNNo = value.orgSNNo
        row.orgId = value.orgId
        // row.longitude = value.longitude
        // row.latitude = value.latitude
        // row = { ...value }
        row = { ...row }
        console.log(row, 'row')
        console.log(1111)
      },
      handleEdit(row, $index) {
        this.$set(row, '_edit', true)
      },
      handleSave(row, $index) {
        var reg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/ // 座机
        var regPhone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if (!(reg.test(row.csmPhone) || regPhone.test(row.csmPhone))) {
          this.$message.error('请输入正确的电话号码')
          return
        }
        if (!row.contact) {
          this.$message.warning('请输入联系人')
          return
        }
        this.$set(row, '_edit', false)
        this.$set(this.tableData01.data, $index, JSON.parse(JSON.stringify(row)))
      },
      handleSave01(row, $index) {
        console.log(row)
        this.$set(row, '_edit', false)
        this.$set(this.tableData02.data, $index, JSON.parse(JSON.stringify(row)))
      },
      del(row, index) {
        this.$confirm('确认要注销吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          // 筛选出使用中的电话
          var doData = this.tableData01.data.filter(l => l.cpStatus === 2)
          if (doData && doData.length === 1) {
            this.$message.warning('唯一的电话不能删除')
            return
          }
          // 如果是默认电话注销   则给下一条加上默认
          if (row.isMain === 1) {
            for (var i = 0; i < this.tableData01.data.length; i++) {
              var item = this.tableData01.data[i]
              if (i !== index && item.cpStatus === 2) {
                item.isMain = 1
                break
              }
            }
          }

          this.tableData01.data[index].isMain = 0
          this.tableData01.data[index].cpStatus = -1
          if (!row.csmId) {
            this.tableData01.data.splice(index, 1)
            return
          }
          const code = {
            csmId: row.csmId,
            csmPhone: row.csmPhone,
            csmPhoneId: row.csmPhoneId
          }
          var res = await deleteCsmPhone(code)
          if (res.success) {
            this.$message.success('注销成功')
          }
        }).catch((e) => {
          console.log(e)
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // })
        })
      },
      del01(row, index) {
        this.$confirm('确认要删除吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.tableData02.data.length === 1) {
            this.$message.warning('唯一的地址不能删除')
            return
          }
          // 如果是默认地址删除   则给下一条加上默认
          if (row.isMain === 1) {
            for (var i = 0; i < this.tableData02.data.length; i++) {
              var item = this.tableData02.data[i]
              if (i !== index) {
                item.isMain = 1
                break
              }
            }
          }
          this.tableData02.data.splice(index, 1)

          this.$message({
            type: 'success',
            message: '成功!'
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // })
        })
      },
      async openLocation(row) {
        await this.$refs.location.open(row)
      },
      // 添加信息
      addMessage01() {
        var reg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/ // 座机
        var regPhone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if (reg.test(this.temp01.csmPhone) || regPhone.test(this.temp01.csmPhone)) {
          // 判断联系人
          if (!this.temp01.contact) {
            this.$message.warning('请输入联系人')
            return
          }

          this.temp01.isMain = 0
          this.temp01.cpStatus = 2

          for (var i = 0; i < this.tableData01.data.length; i++) {
            var item = this.tableData01.data[i]
            if (item.csmPhone === this.temp01.csmPhone) {
              this.$message.warning('电话号码重复 , 无法添加')
              return
            }
          }
          this.tableData01.data.push({ ...this.temp01 })
          this.$set(this.temp01, 'csmPhone', '')
          this.$set(this.temp01, 'contact', '')
        } else {
          this.$message.warning('请输入正确的电话号码')
          return
        }
      },
      addMessage02() {
        if (!this.temp02.orgName) {
          this.$message.warning('请选择就近门市')
          return
        }
        if (this.AddressData.length === 0) {
          this.$message.warning('请选择地址')
          return
        }
        if (!this.temp02.csmAddress) {
          this.$message.warning('请输入详细地址')
          return
        }
        var params = {
          ...this.currentOrg,
          ...this.addressCascader,
          isMain: 0,
          csmAddress: this.temp02.csmAddress,
          csmFloor: this.temp02.csmFloor ? this.temp02.csmFloor : 1
        }
        if (!this.tableData02.data.length) {
          params.isMain = 1
        }
        this.tableData02.data.push(params)
        this.$set(this.tableData02.data, this.tableData02.data.$index, JSON.parse(JSON.stringify(this.temp02)))
        this.$set(this.temp02, 'orgName', '')
        this.$set(this.temp02, 'csmAddress', '')
        this.$set(this.temp02, 'csmFloor', undefined)
        this.AddressData = []
      },
      // 地区
      async selectCascader(val) {
        if (!val) return
        var pathLabels = this.$refs.cascader.getCheckedNodes()[0].pathLabels
        // console.log(pathLabels)
        this.addressCascader = {
          provinceName: pathLabels[0],
          provinceCode: val[0],
          cityName: pathLabels[1],
          cityCode: val[1],
          countryName: pathLabels[2],
          countryCode: val[2],
          streetName: pathLabels[3],
          streetCode: val[3]
        }
      },
      async getAddressList(areaCode = 0) {
        if (areaCode < 0) {
          return []
        }
        var res = await selectAreaCode({ areaCode })
        return res.data
      },
      // 选择省
      async changeProvince(row, column, val) {
        this.cityList = []
        this.countryList = []
        this.streetList = []
        var name = this.provinceList.find(l => l.areaCode === val).areaName
        row[column.property] = name
        row['provinceCode'] = val
        // this.cityList = await this.getAddressList(val) // 获取市
        row['cityCode'] = ''
        row['cityName'] = ''
        row['countryCode'] = ''
        row['countryName'] = ''
        row['streetCode'] = ''
        row['streetName'] = ''

        row = { ...row }
        // console.log(this.cityList)
      // console.log(row,'row[column.property]')
      // console.log(val)
      },
      // 选择市
      async changeCity(row, column, val) {
        this.countryList = []
        this.streetList = []
        var name = this.cityList.find(l => l.areaCode === val).areaName
        row[column.property] = name
        row['cityCode'] = val
        console.log(name)
        row['countryCode'] = ''
        row['countryName'] = ''
        row['streetCode'] = ''
        row['streetName'] = ''
        row = { ...row }
        // this.countryList = await this.getAddressList(val) // 获取街道
      },
      // 选择区
      async changeCountry(row, column, val) {
        this.streetList = []
        var name = this.countryList.find(l => l.areaCode === val).areaName
        row[column.property] = name
        row['countryCode'] = val
        console.log(name)
        row['streetCode'] = ''
        row['streetName'] = ''
        row = { ...row }
        // this.streetList = await this.getAddressList(val) // 获取街道
      },
      // 选择街道
      async changeStreet(row, column, val) {
        var name = this.streetList.find(l => l.areaCode === val).areaName
        row[column.property] = name
        row['streetCode'] = val
        console.log(name)
        row = { ...row }
        console.log(row)
        // this.countryList = await this.getAddressList(val) // 获取街道
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.cpStatus === -1) {
          return 'success-row'
        }
        return ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.form01 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}

.form02 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 50%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
  // .lbTable {
  //   height: 200px;
  // }
}
.contact-tab {
  /deep/ .el-table .success-row {
    background: rgb(220, 220, 220);
  }
  /deep/ .cell .el-input-number--small {
    width: 60px;
  }
}
</style>
